package newcall.com.newcalldemo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.m800.m800demo.R;
import com.m800.verification.M800CountryCode;
import com.m800.verification.M800VerificationClient;
import com.m800.verification.PhoneNumberInfo;

import java.util.ArrayList;
import java.util.List;


public class SelectCountryActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,
        SearchView.OnQueryTextListener {

    public static final String EXTRA_SELECTED_COUNTRY = "selectedCountry";

    private static final String PREFIX_FLAG_IDENTIFIER = "flag_64_";

    private CountryAdapter mAdapter;
    private List<M800CountryCode> mAdapterData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_list_activity);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("国家");
        }

        mAdapter = new CountryAdapter(this);
        PhoneNumberInfo phoneNumberInfo = M800VerificationClient.getVerificationManager(getApplicationContext()).getPhoneNumberInfo();
        if (phoneNumberInfo != null) {
            mAdapterData = phoneNumberInfo.getAllCountryCodes();
            mAdapter.addAll(mAdapterData);
        }
        ListView listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.country_list_menu, menu);
//        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
//        searchView.setOnQueryTextListener(this);
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Intent data = new Intent();
        Gson gson = new Gson();
        String json = gson.toJson(mAdapter.getItem(position));
        data.putExtra(EXTRA_SELECTED_COUNTRY, json);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        // Ignore
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        mAdapter.getFilter().filter(newText);
        return true;
    }

    private class CountryAdapter extends ArrayAdapter<M800CountryCode> {

        private CountryAdapter(Context context) {
            super(context, R.layout.country_list_item);
        }

        @Override
        @NonNull
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext())
                        .inflate(R.layout.country_list_item, parent, false);
                holder = new ViewHolder();
                holder.mCountryFlagImageView = (ImageView) convertView.findViewById(R.id.iv_country_flag);
                holder.mCountryNameTextView = (TextView) convertView.findViewById(R.id.tv_country_name);
                holder.mCallCodeTextView = (TextView) convertView.findViewById(R.id.tv_call_code);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            M800CountryCode m800CountryCode = getItem(position);
            if (m800CountryCode == null) {
                return convertView;
            }

            holder.mCountryNameTextView.setText(m800CountryCode.getName());
            String callCode = "+" + m800CountryCode.getCallCode();
            holder.mCallCodeTextView.setText(callCode);
            int resId = getResources().getIdentifier(PREFIX_FLAG_IDENTIFIER +
                    m800CountryCode.getCountryCode().toLowerCase(), "drawable", getPackageName());
            Glide.with(SelectCountryActivity.this)
                    .load(resId)
                    .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL))
                    .into(holder.mCountryFlagImageView);
            return convertView;
        }

        @Override
        @NonNull
        public Filter getFilter() {
            return mFilter;
        }

        private class ViewHolder {
            private ImageView mCountryFlagImageView;
            private TextView mCountryNameTextView;
            private TextView mCallCodeTextView;
        }

        private Filter mFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                FilterResults filterResults = new FilterResults();
                if (!TextUtils.isEmpty(charSequence)) {
                    List<M800CountryCode> result = new ArrayList<>();
                    for (M800CountryCode item : mAdapterData) {
                        // Check if name matches
                        String name = item.getName();
                        if (name.toLowerCase().contains(charSequence.toString().toLowerCase())) {
                            result.add(item);
                            continue;
                        }
                        // Check if country code matches
                        String countryCode = item.getCountryCode();
                        if (countryCode.toLowerCase().contains(charSequence.toString().toLowerCase())) {
                            result.add(item);
                            continue;
                        }
                        // Check if call code matches
                        String callCode = "+" + item.getCallCode();
                        if (callCode.contains(charSequence.toString().toLowerCase())) {
                            result.add(item);
                        }
                    }
                    filterResults.values = result;
                    filterResults.count = result.size();
                } else {
                    filterResults.values = mAdapterData;
                    filterResults.count = mAdapterData.size();
                }

                return filterResults;
            }

            @Override
            @SuppressWarnings("unchecked")
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                clear();
                if (filterResults.count > 0) {
                    addAll((List<M800CountryCode>) filterResults.values);
                }
                notifyDataSetChanged();
            }
        };
    }
}
